import Taro from '@tarojs/taro-rn';
import React from 'react';

import { getRuntime, ServerHost, uploadUrl } from "./common";
// import { reaction } from "mobx";
export let Runtime = class Runtime {
  constructor() {
    /**
     *
     * 设置存储
     * @param {any} info
     */
    this.setStorage = (key, value) => {
      Taro.setStorageSync(key, value ? JSON.stringify(value) : "");
    };
    /**
     *
     * 获取存储
     * @returns
     */
    this.getStorage = key => {
      var data = Taro.getStorageSync(key);
      if (data) {
        return JSON.parse(data);
      } else {
        return null;
      }
    };
    /**
     *
     * 设置用户信息
     * @param {any} info
     */
    this.setUserInfo = info => {
      Taro.setStorageSync("user", info ? JSON.stringify(info) : "");
    };
    /**
     *
     * 获取用户信息
     * @returns
     */
    this.getUserInfo = () => {
      var data = Taro.getStorageSync("user");
      if (data) {
        return JSON.parse(data);
      } else {
        return null;
      }
    };
    /**
     * 获取token
     */
    this.getToken = () => {
      const user = this.getUserInfo();
      if (!user) return '';
      return { Authorization: "Bearer " + (user && user.token || '') };
      // return { Authorization: "Bearer LJ3wfBJIZ43UiiEwgw-pWsOIKNSV07-cDKv8rBCEqEQ3sikovZbiIpI7LeSBwdq278PZWyMrbJe1rr_ZMvwlj3qBORgvjQ2JHsFc5Zb8tWnfpsV7VQi-Nq27fNrM7zBFpWsxow_9FBWNLW9fYqEAmsx86HEePmvBm3Jbpr8O7b08fpV9QzRiR8hWrzeeZMiPRSfJ-NdpqJX2A8UPDG5nwPmSE7dK3-5qcJfGBelP6ROa5-Dy8ion31VZYRmYt8KbOggc9RFy-GPyL8Zp232Si8JdoTJyoW4Gpj9AYmrHrZh8uRGzqawq1GXHMl5Ma712UM4ZX_ThZAglcDL4u5xr_kbb_jTAK38q9zZYD5G8Z_C1rJd2yVby_BS7wyx99y2MFV6249t1I9hqVwJxdFU9PcNux1eyltUNibDGMXLzjLv2EDCIN11O-Y6-x6GmKdkNkzrLlMlhwxuWzzw70n0h_yywBkPFPZPMTodf7stFuEHI_EKHjzb3GgEgmBSI09cE" };
    };
    this.isLogin = () => {
      if (!localStorage.token) {
        // return false;
        return "请先登录";
      } else {
        return true;
      }
    };
    this.navigateTo = (url, isNeedLogin = false) => {
      if (!getRuntime().getToken() && isNeedLogin) {
        getRuntime().navigateTo('/pages/login/login');
        return;
      }
      Taro.navigateTo({
        url: url
      });
    };
    this.redirectTo = url => {
      Taro.redirectTo({
        url: url
      });
    };
    this.navigateBack = () => {
      Taro.navigateBack({
        delta: 1
      });
    };
    this.switchTab = url => {
      Taro.switchTab({
        url: url
      });
    };
    this.pageScrollToTop = () => {
      Taro.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    };
    this.pageScrollTo = scrollTop => {
      Taro.pageScrollTo({
        scrollTop: scrollTop,
        duration: 300
      });
    };
    this.showToast = (title, icon) => {
      Taro.showToast({
        title: title,
        icon: icon || 'none',
        mask: true
      });
    };
    this.showModal = (title, content = '', callback) => {
      Taro.showModal({
        title: title,
        content: content
      }).then(res => {
        if (res.confirm) {
          callback();
        }
      });
    };
    this.makePhoneCall = phoneNumber => {
      Taro.makePhoneCall({
        phoneNumber: phoneNumber
      });
    };
    this.wxloginout = () => {
      this.setUserInfo();
      Taro.clearStorage();
    };
    this.wxlogin = (res, getToken, fail) => {
      const user = this.getUserInfo();
      if (user) return;
      const that = this;
      Taro.login({
        success: function (loginres) {
          if (loginres.code && res.encryptedData) {
            that.setStorage("code", { code: loginres.code });
            const info = {
              code: loginres.code,
              ...res
            };
            console.log(info);
            getToken(info);
          } else {
            fail();
          }
        }
      });
    };
    this.getwxcode = callback => {
      Taro.login({
        success: function (loginres) {
          callback(loginres.code);
        }
      });
    };
    this.wxauth = (name, callback) => {
      Taro.getSetting({}).then(res => {
        if (res.authSetting[name]) {
          callback(true);
        } else {
          callback(false);
        }
      }).catch(e => {
        callback(false);
      });
    };
    this.upload = (callback, count = 1) => {
      Taro.chooseImage({
        count: count,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }).then(res => {
        console.log(res);
        Taro.showLoading({
          title: '加载中...'
        });
        Taro.uploadFile({
          url: ServerHost + uploadUrl,
          header: this.getToken(),
          filePath: res.tempFilePaths[0],
          name: 'file'
        }).then(res1 => {
          Taro.hideLoading();
          if (res1.statusCode == 200) {
            const data = JSON.parse(res1.data);
            if (data.success) {
              callback(data.result);
              // this.setState({ avatar: data.result });
            } else {
              this.showToast(data.error.message, 'none');
            }
          } else {
            this.showToast(res1['errMsg'], 'none');
          }
        });
      });
    };
    this.upIdCard = (callback, type = 1) => {
      Taro.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album']
      }).then(res => {
        Taro.showLoading({
          title: '加载中...'
        });
        Taro.uploadFile({
          url: ServerHost + uploadUrl,
          header: this.getToken(),
          filePath: res.tempFilePaths[0],
          name: 'file'
        }).then(res1 => {
          Taro.hideLoading();
          if (res1.statusCode == 200) {
            const data = JSON.parse(res1.data);
            if (data.success) {
              callback(data.result);
            } else {
              this.showToast(data.error.message, 'none');
            }
          } else {
            const data = JSON.parse(res1.data);
            this.showToast(data.error.message, 'none');
          }
        });
      });
    };
    /**
     * 图片上传
     * @param files
     * @param callback
     */
    this.uploadFile = (files, callback) => {
      let images = Array();
      for (var i = images.length; i < files.length; i++) {
        const file = files[i]['file']['path'];
        Taro.showLoading({ title: '图片上传中...' });
        Taro.uploadFile({
          url: ServerHost + uploadUrl,
          header: this.getToken(),
          filePath: file,
          name: 'file'
        }).then(res1 => {
          Taro.hideLoading();
          if (res1.statusCode == 200) {
            const data = JSON.parse(res1.data);
            if (data.success) {
              images.push(data.result);
              if (images.length == files.length) this.showToast('图片上传成功~');
              callback(images);
            } else {
              this.showToast(data.error.message, 'none');
            }
          } else {
            this.showToast(res1['errMsg'], 'none');
          }
        }).catch(error => {
          Taro.hideLoading();
          console.log(error);
        });
      }
    };
    //下拉刷新
    this.pullDownRefresh = callback => {
      Taro.showNavigationBarLoading(); //在标题栏中显示加载
      callback();
      Taro.hideNavigationBarLoading(); //在标题栏中显示加载
      Taro.stopPullDownRefresh();
    };
    this.createSelectorQuery = () => {
      return Taro.createSelectorQuery();
    };
    this.scanCode = callback => {
      Taro.scanCode().then(res => {
        callback(res.result);
      });
    };
    this.getLocation = callback => {
      Taro.getLocation({
        type: 'wgs84'
      }).then(res => {
        callback(res.latitude, res.longitude);
      });
    };
    this.chooseLocation = callback => {
      Taro.chooseLocation().then(res => {
        callback(res.name, res.address, res.latitude, res.longitude);
      });
    };
    this.openLocation = (latitude, longitude) => {
      Taro.openLocation({ latitude, longitude });
    };
    this.wxPay = (payParams, callback) => {
      const that = this;
      Taro.requestPayment({
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType,
        paySign: payParams.paySign,
        success(res) {
          // console.log(res);
          callback();
        },
        fail(res) {
          console.log(res);
          that.showToast("支付失败");
        }
      });
    };
    this.isEmpty = str => {
      if (typeof str == "undefined" || str == null || str == "") {
        return true;
      } else {
        return false;
      }
    };
  }
  commonPay(orderId, custom, isPayPoints = false, callBack) {
    let payUrl = `${ServerHost}/api/Account/PaymentParameters?orderId=${orderId}&custom=${custom}&isPayPoint=${isPayPoints}`;
    let user = getRuntime().getUserInfo();
    let token = user && user.token ? 'Bearer ' + user.token : '';
    fetch(payUrl, {
      method: 'GET',
      headers: { 'Authorization': token }
    }).then(response => response.json()).then(response => {
      console.log(response);
      if (response.msg === 'ok') {
        getRuntime().wxPay(response, () => {
          callBack && callBack();
        });
      } else {
        getRuntime().showToast(response.msgtext);
      }
    }).catch(() => {
      getRuntime().showToast('获取支付参数失败~');
    });
  }
};